
<template>
    <div id="dataView" :class="{ full: fullscreen }">
        <!-- <breadcrumb :data="breadList" v-if="!fullscreen"></breadcrumb> -->
        <data-table-view :value="tableViewData" v-show="viewMode === 2" @modeChange="viewMode = 1"></data-table-view>
        <div class="canvas" ref="adaptive" id="adaptive"
         :style="{
            background: sceneBgColor,
            position: 'relative',
            width: '100%',
            overflow: 'hidden' }" :class="{
            hide: viewMode === 2,
            fixed: fullscreen
        }">
            <div id="adaptiveBg" refs="adaptiveBg" :class="{
                nowrap: !lineWrap
            }" :style="{
                transform: `scale(${layerScale}, ${layerScale})`,
                whiteSpace: 'nowrap',
            }">
                <!-- 母线节点  -->
                <div class="branch-item"  v-for="(item,itemInx) in mapViewData"
                    :key="itemInx" :style="{
                        width: getBranchWidth(item) 
                    }">
                        <!-- 母线设备数据 -->
                    <!-- <table class="table-data"
                        v-for="(row, index) in item.devTableList" :key="'dev' + index">
                        <tr v-for="(td, rowIndex) in row" :key="'devRow' + rowIndex">
                            <td :style="{ color: fontColor }" v-for="(item, itemIndex) in td" :key="'devTd' + itemIndex"
                                :id="item.id" :class="{ off: item.onlineStatus === 0 }" :colspan="item.length || 1"
                                :rowspan="item.rowLength || 1" v-html="item.text"></td>
                        </tr>
                    </table> -->
                    <!-- 线路 -->
                    <div class="branch-content"
                        :style="{
                        width: (branchLineMargin*item.maxwidth) + 'px',
                        borderTop: item.type === 'contact' || item.type === 'empty' ? 'none' : '2px solid ' + lineColor }"
                        v-if="item.type !== 'contact' && item.type !== 'empty'">
                        <div class="branch-dot" :style="{ background: lineColor }"></div>
                        <div class="branch-line" 
                        :class="{ 'branch-line-active': item.online>0 }" 
                        :style="{
                            background: lineColor,
                            height: branchLineSize + 'px' 
                        }">
                        </div>
                        <!-- 是否有图片 -->
                        <!-- <div class="branch-img" v-if="item.lineDevModelUrlBelow" :style="{
                            background: sceneBgColor,
                            top: 12 + 'px'}">
                            <img :src="item.lineDevModelUrlBelow" alt="" />
                        </div> -->
                        <branch-svg v-if="!item.lineDevModelUrlBelow" :color="lineColor"
                        :bgColor="sceneBgColor"></branch-svg>
                        <img class="branch-div-img" v-if="item.online>0" src="@/assets/images/jiantou_d.png" alt="" />
                        <div class="branch-div-table" :style="{bottom: item.senserList&&item.senserList.length>0 ? '-20px' : '0' }" v-if="item.senserList&&item.senserList.length>0">
                            <el-popover :width="650" placement="top">
                                <template #reference>
                                    <div class="branch-div" >
                                        设备信息
                                    </div>
                                </template>
                                <template #default>
                                    <el-table :data="item.senserList" max-height="300px">
                                        <el-table-column width="150" align="center" property="snsName" label="名称" />
                                        <el-table-column width="200" align="center" property="snsTypeDetail" label="传感器类型" />
                                        <el-table-column width="200"  align="center"property="snsCode" label="编号" />
                                        <el-table-column width="100" align="center" property="onlineStatus" label="离线"  >
                                            <template #default="scope">
                                                <span v-if="scope.row.onlineStatus === 0" style="color: red;">离线</span>
                                                <span v-else style="color: green;">在线</span>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </template>
                            </el-popover>
                        </div>
                        <div class="branch-name-gh" v-if="item.cabinet" :style="{ color: fontColor }">
                            {{ '柜号：' + item.cabinet  }}
                        </div>
                        <div class="branch-name" :style="{ color: fontColor,bottom: item.senserList&&item.senserList.length>0 ? '-40px' : '-20px' }"  :class="{ 'branch-name-active': item.online>0 }"  >
                            {{ item.branchName }}
                        </div>
                        <div class="branch-master-name" :class="item.cls" :style="{
                            background: lineColor,
                            color: masterNameFontColor
                        }">
                         {{ item.masterName }} 
                        </div>
                          <!-- 递归展示支线 -->
                        <div v-if="item.branchList && item.branchList.length > 0" 
                            :style="{ paddingLeft:(branchLineMargin/2) + 'px', }"
                            class="sub-branch-container">
                            <BranchItem
                                v-for="(subItem, subIndex) in item.branchList"
                                :key="subIndex"
                                :branch-item="subItem"
                                :branch-line-margin="branchLineMargin"
                                :branch-line-size="branchLineSize"
                                :line-color="lineColor"
                                :font-color="fontColor"
                                />
                        </div>
                      </div>
                    <!-- 母线连接 -->
                    <div class="branch-contact" :style="{ borderColor: lineColor }" v-if="item.type === 'contact'">
                        <contact-svg :color="lineColor" :bgColor="sceneBgColor" :relatedType="item.relatedType">
                        </contact-svg>
                    </div>
                </div>
            </div>
        </div>
        <div class="control" v-show="viewMode === 1">
            <div class="status">
                <span :style="{ color: fontColor }">连接状态：</span>
                <div class="icon icon-success" v-if="isConnected"></div>
                <div class="icon icon-error" v-else></div>
            </div>
            <div class="title">{{ stationName }}</div>
            <div class="btn">
                <el-button type="text" class="text">{{ layerScale.toFixed(2) }}X</el-button>
                <el-button icon="setting" @click="modalShow = true">控制面板</el-button>
                <!-- <el-button icon="el-icon-full-screen" @click="handleFullScreen">全屏切换</el-button> -->
                <!-- <el-button icon="data-board" @click="viewMode = 2">查看线路表</el-button> -->
            </div>
        </div>
        <div class="alarm" v-if="alarmShow && viewMode === 1" @click="$router.push('/alarm')">
            <!-- <img class="alarm-icon" src="@/assets/img/dangerous.png" alt="" /> -->
            {{ alarmText }}
            <div class="alarm-close el-icon-close" @click.stop="alarmShow = false"></div>
        </div>

        <div class="footer" v-show="viewMode === 1">
            <div class="date" v-if="nowDate">当前时间：{{ nowDate }}</div>
        </div>
        <modal title="控制面板" v-model="modalShow" @confirm="updateSetting" @closed="modalShow = false" width="800px">
            <el-form ref="settingForm" label-width="120px" label-position="right" label-suffix=":" :model="settingForm"
                :inline="true">
                <el-row>
                </el-row>
                <el-row style="margin: 20px 0">
                    <el-col :span="6">
                        <el-form-item prop="sceneBgColor" label="背景颜色">
                            <el-color-picker v-model="settingForm.sceneBgColor">
                            </el-color-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="lineColor" label="线路颜色">
                            <el-color-picker v-model="settingForm.lineColor">
                            </el-color-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="fontColor" label="字体颜色">
                            <el-color-picker v-model="settingForm.fontColor">
                            </el-color-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="fontColor" label="母线字体颜色">
                            <el-color-picker v-model="settingForm.masterNameFontColor">
                            </el-color-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </modal>
          <!-- 原模板内容 -->
        <MessagePopup ref="messagePopupRef" :show="hasNewMessage" @close="hasNewMessage = false" />
    </div>
</template>

<script>
import Breadcrumb from '@/components/cloudTv/Breadcrumb'
import ContactSvg from '@/components/cloudTv/ContactSvg'
import BranchSvg from '@/components/cloudTv/BranchSvg'
import BranchItem from './BranchItem.vue';
import Modal from '@/components/cloudTv/Modal'
import dataTableView from './dataTableView'
import { pointDataFormat } from '@/utils/utils'
import { faultType } from '@/utils/type'
import { filterTime } from '@/utils/filterTime'
import { useWebSocket } from '@/utils/useWebSocket.js'; // 引入自定义的 WebSocket 钩子函数
import MessagePopup from '@/components/MessagePopup';// 消息弹窗
import { useInfoStore } from '@/store/modules/info.js'
const userInfo = useInfoStore();


export default {
    name: 'dataView',
    data() {
        return {
            breadList: [
                {
                    name: '企业管理'
                },
                {
                    name: '监测站管理'
                },
                {
                    name: '线路总览'
                }
            ],
            faultType,
            settingForm: {
                branchLineSize: 280,
                branchLineMargin: 280,
                // tableFontSize: 30,
                // branchModel: 2,
                lineWrap: true,
                alarmSond: true,
                fontColor: '#ffffff',
                masterNameFontColor: '#ffffff',
                lineColor: '#d9a116',
                sceneBgColor: '#212120'
            },
            predefineColors: [
                'rgba(202,0,3,1)',
                'rgba(4,166,53,1)',
                'rgba(255,235,0,1)'
            ],
            // mp3: require('@/assets/sond/alarm.mp3'), // 报警声音
            modalShow: false, // 设置弹窗
            drag: false, // 是否开始拖动
            dragStart: [0, 0], // 开始拖动定位
            layerPos: [], // 当前背景层定位
            sceneBg: {}, // 背景场景
            scene: {}, // 场景
            mapData: [], // 电路图数据
            mapViewData: [], // 电路图数据
            tableViewData: [], // 电路图表格数据
            lineMargin: 350, // 母线间距
            branchLineSize: 280, // 支线长度
            branchLineMargin: 180, // 支线间距
            branchModel: 2, // 1交错显示 2同向显示
            tableFontSize: 30, // 表格字体
            lineWrap: true, // 是否自动换行
            lineColor: '#d9a116', // 线路颜色
            sceneBgColor: '#212120', // 背景颜色
            fontColor: '#ffffff', // 字体颜色
            masterNameFontColor: '#ffffff', // 母线字体颜色
            linkStatus: 0, // 连接状态
            fullscreen: false, // 是否全屏
            alarmShow: false, // 报警弹窗
            alarmText: '', // 报警内容
            viewMode: 1, // 1线路图模式 2线路表模式
            stationConfig: {}, // 站点显示配置
            alarmSond: true,
            isSceneInit: false,
            layerScale: 1,
            tableDataPos: [],
            clientLeft: 0,
            clientTop: 0,
            canvasTableTop: 100,
            canvasTableLeft: 30,
            canvasTablePos: [],
            deviceImg: '',
            stationName: '',
            entId: '',
            nowDate: '',
            xNow: 0,
            yNow: 0,
            configId: 0, //站点配置id,
            // web socket
            isConnected: null,
            hasNewMessage: null,
            sendMessage: null,
            on: null,
            destroy: null,
            initWebSocket: null,
            config: null,
        }
    },
    components: {
        Breadcrumb,
        dataTableView,
        Modal,
        BranchSvg,
        ContactSvg,
        BranchItem,
        MessagePopup 
    },
    beforeUnmount() {
        document.body.onresize = null
        clearInterval(this.nowDateInterval)
        this.linkStatus = -1;
        // 销毁连接
        this.destroy();
    },
    mounted() {
        // this.getNowDate(); //获取当前时间
        this.eventFullScreen(); //全屏切换
        this.stationId = this.$route.query.id;
        this.entId = this.$route.query.entId;
        const staCode = this.$route.query.staCode;
        this.getDataList(); //获取数据
        this.getStationConfig(); //获取站点显示配置
        // 订阅自定义消息事件 ---------------
        // 个人信息
        const account = userInfo.info.account;//账号
        const wsUrl = `${import.meta.env.VITE_APP_WS_URL}?uno=${account}&role=${staCode}`
        const { isConnected, hasNewMessage, sendMessage, on, destroy, initWebSocket, config,
        } = useWebSocket(wsUrl, {
            reconnectTimes: 3, // 自定义重连次数
            heartbeatInterval: 30000 // ms自定义心跳间隔
        });
        this.isConnected = isConnected;
        this.hasNewMessage = hasNewMessage;
        this.sendMessage = sendMessage;
        this.on = on;
        this.destroy = destroy;
        this.initWebSocket = initWebSocket;
        this.config = config;
        this.on('onMessage', (msg) => {
            let mockEvent =  JSON.parse(msg);
            if(mockEvent.type==1){ //刷新接口数据
                this.getDataList()
            }
        });
        this.initWebSocket();
    },
    methods: {
        getDataList() {
            this.cloudTv_API.GetStationDevLineCfg({
                id: this.stationId,
            }).then(res => {
                let mapData = res.data.masterLineList
                this.addDataTable(mapData)
                this.mapData = mapData
                this.tableViewData = mapData
                this.stationName = res.data.stationName
                this.formatMapData()
            });
        },
        drawConnections() {
            const svg = this.$refs.connectionSvg;
            if (!svg) return;
            // 清空之前的连接线
            while (svg.firstChild) {
                svg.removeChild(svg.firstChild);
            }
            const offlineBranches = [];
            // 递归函数，用于遍历所有嵌套的分支
            const findOfflineBranches = (items, index = 0) => {
                items.forEach((item) => {
                    if (item.online > 0) {
                        // 查找对应的 .branch-line 元素
                        const adaptiveBg = document.getElementById('adaptiveBg');
                        const branchLines = adaptiveBg ? adaptiveBg.querySelectorAll('.branch-line') : [];
                        const element = branchLines[index];
                        
                        if (element) {
                            const rect = element.getBoundingClientRect();
                            const adaptiveRect = this.$refs.adaptive.getBoundingClientRect();
                            offlineBranches.push({
                                // x: rect.left - adaptiveRect.left + element.offsetWidth / 2,
                                // y: rect.top - adaptiveRect.top + element.offsetHeight
                                x: rect.x,
                                y: rect.y 
                            });
                            index++;
                        }
                    }
                    if (item.branchList && item.branchList.length > 0) {
                        index = findOfflineBranches(item.branchList, index);
                    }
                });
                return index;
            };

            findOfflineBranches(this.mapViewData);
            console.log(offlineBranches);
            
            if (offlineBranches.length < 2) return;

            let path = `M ${offlineBranches[0].x} ${offlineBranches[0].y}`;
            for (let i = 1; i < offlineBranches.length; i++) {
                path += ` L ${offlineBranches[i].x} ${offlineBranches[i].y}`;
            }
            const pathElement = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            pathElement.setAttribute('d', path);
            pathElement.setAttribute('stroke', 'red');
            pathElement.setAttribute('stroke-width', '2');
            pathElement.setAttribute('fill', 'none');
            svg.appendChild(pathElement);
         },
          // 获取站点显示配置
          getStationConfig() {
            this.cloudTv_API.GetStationByStation({
                staID: this.stationId,
            }).then(res => {
                if(res.data){
                    let config = JSON.parse(res.data.config)
                    this.configId = res.data.id;
                    if (config.lineWrap === undefined) {
                        config.lineWrap = true
                    }
                    if (config.branchLineSize === undefined) {
                        config.branchLineSize = 280
                    }
                    if (config.branchLineMargin === undefined) {
                        config.branchLineMargin = 180
                    }
                    if (config.lineColor === undefined) {
                        config.lineColor = '#d9a116'
                    }
                    if (config.sceneBgColor === undefined) {
                        config.sceneBgColor = '#212120'
                    }
                    if (config.fontColor === undefined) {
                        config.fontColor = '#ffffff'
                    }
                    if (config.masterNameFontColor === undefined) {
                        config.masterNameFontColor = '#ffffff'
                    }
                    if (config.alarmSond === undefined) {
                        config.alarmSond = true
                    }
                    // this.branchLineSize = config.branchLineSize
                    // this.branchLineMargin = config.branchLineMargin
                    this.lineWrap = config.lineWrap
                    this.lineColor = config.lineColor
                    this.sceneBgColor = config.sceneBgColor
                    this.fontColor = config.fontColor
                    this.masterNameFontColor = config.masterNameFontColor
                    this.alarmSond = config.alarmSond
                    this.settingForm = config
                }
            });
        },
        // 获取当前时间
        getNowDate() {
            this.nowDateInterval = setInterval(() => {
                this.nowDate = filterTime(new Date().getTime(), 'yyyy-mm-dd hh:ff:ss')
            }, 1000)
        },
        // 生成表格数据
        addDataTable(mapData) {
            for (let i = 0; i < mapData.length; i++) {
                let children = []
                if (mapData[i].branchList) { // 无设备 单层遍历即可
                    mapData[i].branchList.forEach((branch, branchIndex) => {
                        branch.tableList = []
                        if(branch.senserList){//有数据才调用
                            branch.tableList = this.createSenserTable(branch.senserList) //格式化数据展示
                        }
                        branch.maxLength = this.findListMax(branch.tableList)
                        children.push(branch)
                    })
                }
                mapData[i].children = children.sort((a, b) => {
                    return a.lineDevShowOrder - b.lineDevShowOrder
                })
                mapData[i].children.forEach((item, index) => {
                    if (item.devTableList && index !== 0) {
                        let devTableList = JSON.parse(JSON.stringify(item.devTableList))
                        delete item.devTableList
                        mapData[i].children[0].devTableList = devTableList
                    }
                })
            }

        },
        // 线路数据格式化
        formatMapData() {
                 // 获取电路图的原始数据
                let mapData = this.mapData;
                console.log(mapData);
                // 存储所有有前置线路的线路
                let concatData = []
                for (let i = 0; i < mapData.length; i++) {
                    if (mapData[i].preLineId) {
                        concatData.push(mapData[i])
                    }
                }
                // 补充缺失的前置线路到 concatData 中
                for (let i = 0; i < concatData.length; i++) {
                    let preIndex = concatData.findIndex(item => item.id === concatData[i].preLineId)
                    if (preIndex === -1) {
                        let preItem = mapData.find(item => item.id === concatData[i].preLineId)
                        if (preItem) {
                            concatData.push(preItem)
                        }
                    }
                }
              
                // 存储按顺序排列的关联线路
                let newConcatData = []
                for (let i = 0; i < concatData.length; i++) {
                    if (!concatData[i].preLineId) {
                        newConcatData.push(concatData[i])
                        findNextItem(concatData[i].id)
                    }
                }
                 // 递归函数，用于找出下一个关联线路并添加到 newConcatData 中
                function findNextItem(id) {
                    let nextItem = concatData.find(item => item.preLineId === id)
                    if (nextItem) {
                        newConcatData.push(nextItem)
                        if (concatData.find(item => item.preLineId === nextItem.id)) {
                            findNextItem(nextItem.id)
                        }
                    }
                }
                concatData = newConcatData
                // 存储独立线路
                let singleData = []
                for (let i = 0; i < mapData.length; i++) {
                    if (concatData.findIndex(item => item.id === mapData[i].id) === -1) {
                        singleData.push(mapData[i])
                    }
                }
                // 合并按顺序排列的关联线路和独立线路
                let row = [...concatData, ...singleData]
                // 存储最终用于页面展示的数据
                let mapViewData = []
                for (let i = 0; i < row.length; i++) {
                    for (let j = 0; j < row[i].children.length; j++) {
                        let item = row[i].children[j]
                        item.masterLineId = row[i].id
                        item.masterName = row[i].masterName
                        item.relatedType = row[i].relatedType
                        mapViewData.push(item)
                    }
                    if (row[i + 1] && row[i + 1].children.length) {
                        mapViewData.push({
                            type: row[i + 1].relatedType ? 'contact' : 'empty',
                            relatedType: row[i + 1].relatedType
                        })
                    }
                }
                // 递归添加 maxwidth 字段
                function addMaxWidth(item) {
                    let currentSum = 0;
                    // 计算 maxwidth2 字段，仅为当前下级 branchList 的长度
                    item.maxwidth2 = item.branchList ? item.branchList.length : 1;
                    if (item.branchList && item.branchList.length > 0) {
                        // 累加当前节点的 branchList 长度
                        currentSum = item.branchList.length;
                        // 遍历子节点，递归计算子节点及其子节点的长度总和
                        item.branchList.forEach(subItem => {
                            currentSum += addMaxWidth(subItem);
                        });
                    }
                    // 存储当前节点的 maxwidth
                    item.maxwidth = currentSum + 1;
                    return currentSum;
                }
                // 对 mapViewData 中的每个项调用递归函数
                mapViewData.forEach(item => {
                    addMaxWidth(item);
                });
                // 处理母线名称的显示位置
                this.mapViewData = this.showMasterNameClass(mapViewData)
                console.log( this.mapViewData);
                
                // 在 DOM 更新完成后进行事件绑定操作
                this.$nextTick(() => {
                    if (!document.getElementById('adaptive').onmousedown) {
                        this.layerEventBind()
                    }
                    //   this.drawConnections();   

                })
        },
        // 生成传感器表格，参数list为/wholeStruct的senserList
        createSenserTable(list) {
            // 去重
            let chkSnsTypeList = {}
            const ary = []
            for (let i = 0; i < list.length; i++) {
                let key = list[i].snsType
                if (list[i].position) {
                    key = list[i].snsType + list[i].position
                }
                if (!chkSnsTypeList[key] && /温度采集器|电机|过电压保护器|充电柜（900B）|接地管理|脉冲采集器|快切状态/.test(list[i].snsType)) {
                    console.log('snsTypeKey[' + key + ']')
                    chkSnsTypeList[key] = 1
                    ary.push(list[i])
                }
            }
            // console.log('1 ary:' + JSON.stringify(ary))
            // 归类
            let snsTypeKey = {}
            for (let i = 0; i < ary.length; i++) {
                let item = ary[i]
                // console.log('支线详情：' + JSON.stringify(item))
                if (!snsTypeKey[item.snsType]) {
                    snsTypeKey[item.snsType] = [item]
                } else {
                    snsTypeKey[item.snsType].push(item)
                }
            }
            // console.log('2 snsTypeKey:' + JSON.stringify(snsTypeKey))
            // 生成传感器图表
            let canvasTableList = []
            for (let key in snsTypeKey) {
                let itemList = snsTypeKey[key]
                const table = pointDataFormat(key, itemList, 2)
                canvasTableList.push(table)
            }
            return canvasTableList
        },
        // 查找数组最大长度项
        findListMax(list) {
            let max = 0
            list.forEach(item => {
                if (item.length > max) {
                    max = item.length
                }
            })
            return max
        },
        // 背景事件绑定
        layerEventBind() {
            const adaptive = document.getElementById('adaptive')
            const adaptiveBg = document.getElementById('adaptiveBg')
            const _this = this
            // 滚轮缩放
            adaptive.addEventListener('mousewheel', e => {
                let wheel = e.wheelDelta || -e.detail
                let delta = Math.max(-1, Math.min(1, wheel))
                let layerScale = this.layerScale
                if (delta < 0) {
                    layerScale = layerScale - 0.05
                    layerScale = layerScale <= 0.1 ? 0.1 : layerScale
                }
                if (delta > 0) {
                    layerScale = layerScale + 0.05
                    layerScale = layerScale >= 3 ? 3 : layerScale
                }
                this.layerScale = layerScale
            })

            // 鼠标拖拽
            adaptive.onmousedown = function (e) { // 鼠标按下事件
                e = e || window.event // 事件对象
                var xDown = e.clientX // 鼠标按下X的坐标
                var yDown = e.clientY // 鼠标按下Y的坐标
                var leftDown = adaptiveBg.offsetLeft // 获取盒子的初始left值
                var topDown = adaptiveBg.offsetTop // 获取盒子的初始top值
                _this.xNow = 0
                _this.yNow = 0
                document.onmousemove = function (e) { // 鼠标移动事件
                    e = e || window.event
                    var xMove = e.clientX // 鼠标移动X的坐标
                    var yMove = e.clientY // 鼠标移动Y的坐标
                    // 移动的坐标减去按下的坐标 = 移动的距离
                    _this.xNow = xMove - xDown
                    _this.yNow = yMove - yDown
                    // 赋值给left和top
                    adaptiveBg.style.top = topDown + _this.yNow + 'px'
                    adaptiveBg.style.left = leftDown + _this.xNow + 'px'
                }
                document.onmouseup = function () { // 鼠标抬起事件
                    // 清除移动和抬起事件
                    this.onmousemove = this.onmouseup = null
                }
                return false // 阻止默认事件
            }

            if (!document.contains) {
                document.contains = document.documentElement.contains
            }

            document.body.onresize = () => {
                if (this.isSceneInit) {
                    return
                }
                this.isSceneInit = true
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.mapViewData = this.showMasterNameClass(this.mapViewData)
                        this.isSceneInit = false
                    }, 200)
                })
            }
        },
        // 全屏切换事件监听
        eventFullScreen() {
            const changeStatus = () => {
                this.fullscreen = !this.fullscreen
            }
            document.addEventListener('fullscreenchange', changeStatus)
            document.addEventListener('mozfullscreenchange', changeStatus)
            document.addEventListener('webkitfullscreenchange', changeStatus)
            document.addEventListener('msfullscreenchange', changeStatus)
        },
        // 全屏切换
        handleFullScreen() {
            const _this = this
            const element = document.documentElement
            function fullScreen() {
                if (element.requestFullscreen) {
                    element.requestFullscreen()
                } else if (element.webkitRequestFullScreen) {
                    element.webkitRequestFullScreen()
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen()
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen()
                }
                _this.fullscreen = true
                console.log('已全屏！')
            }

            function exitFullScreen() {
                if (document.exitFullscreen) {
                    document.exitFullscreen()
                } else if (document.webkitCancelFullScreen) {
                    document.webkitCancelFullScreen()
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen()
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen()
                }
                console.log('已还原！')
                _this.fullscreen = false
            }
            if (document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen || document.msFullscreenElement) {
                exitFullScreen()
            } else {
                fullScreen()
            }
        },
        // 修改配置
        updateSetting() {
            this.cloudTv_API.EditStationCFG({
                id: this.configId,
                staID: this.stationId,
                config: JSON.stringify(this.settingForm),
            }).then(res => {
                // this.getStationConfig(); //获取站点显示配置
                this.lineMargin = this.settingForm.lineMargin
                // this.branchLineSize = this.settingForm.branchLineSize
                // this.branchLineMargin = this.settingForm.branchLineMargin
                this.lineWrap = this.settingForm.lineWrap
                this.tableFontSize = this.settingForm.tableFontSize
                this.branchModel = this.settingForm.branchModel
                this.lineColor = this.settingForm.lineColor
                this.sceneBgColor = this.settingForm.sceneBgColor
                this.masterNameFontColor = this.settingForm.masterNameFontColor
                this.fontColor = this.settingForm.fontColor
                this.alarmSond = this.settingForm.alarmSond
                // this.formatMapData()
                this.modalShow = false;
            })
        },
        // 获取支线宽度
        getBranchWidth(item) {
            if (item.type === 'empty') {
                return 80 + 'px'
            } else if (item.type === 'contact') {
                return 84 + 'px'
            } else {
                return this.branchLineMargin *  + 'px'
            }
        },
        // 判断母线名称显示位置
        showMasterNameClass(list) {
            let ary = [...list]
            // let maxWidth = document.getElementById('adaptiveBg').clientWidth
            // let rowWidth = 0
            ary.forEach((item, index) => {
                item.cls = 'middle'
                // let nextItem = ary[index + 1]
                // let perItem = ary[index - 1]
                // if (!nextItem && perItem && !perItem.type) {
                //     item.cls = 'none'
                // }
                // if (nextItem && nextItem.type && perItem && !perItem.type) {
                //     item.cls = 'none'
                // }
                // if (((nextItem && nextItem.type) || !nextItem) && ((perItem && perItem.type) || !perItem)) {
                //     item.cls = 'middle'
                // }
                // let curWidth = /contact|empty/.test(item.type) ? 84 : this.branchLineMargin
                // rowWidth = rowWidth + curWidth
                // if (rowWidth > maxWidth) {
                //     rowWidth = curWidth
                //     if (ary[index - 2] && ary[index - 2].type) {
                //         perItem.cls = 'middle'
                //     } else {
                //         perItem.cls = 'none'
                //     }
                //     if (nextItem && nextItem.type) {
                //         ary[index].cls = 'middle'
                //     }
                // }
            })
            return ary
        },
    } 
}
</script>

<style lang="scss">
.el-scrollbar__view {
    height: 100%;
}
.branch-line-active {
    background-image: url('@/assets/images/jiantou.png') !important; // 引入图片
    background-size: 100%  !important; 
    padding-right: 10px !important ;
    background-repeat: repeat-y !important; // 图片垂直重复
    animation: imageScroll 3s linear infinite !important; // 应用动画，2s 完成一次滚动，线性匀速，无限循环
}
// 定义箭头移动的关键帧动画
@keyframes imageScroll {
    0% {
        background-position: 0 0;
    }
    100% {
        background-position: 0 100%;
    }
}

.branch-name-active {
    color: #d81e06 !important; // 文字变红
    font-weight: bold !important; // 加粗
    animation: scaleAnimation 1.4s ease-in-out infinite;
}
// 定义放大缩小的关键帧动画
@keyframes scaleAnimation {
    0% {
        transform: translateX(-50%) scale(1); // 初始状态
    }
    50% {
        transform: translateX(-50%) scale(1.3); // 放大到 1.2 倍
    }
    100% {
        transform: translateX(-50%) scale(1); // 恢复初始大小
    }
}

@keyframes alarmShadow {
    0% {
        box-shadow: 0px 0px 6px #ff0000;
    }

    100% {
        box-shadow: 0px 0px 22px #ff0000;
    }
}

#dataView {
    // width: 100%;
    min-width: 100%;
    height: 100%;
    position: relative;
       // ... 其他代码 ...
    .connection-svg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
    }
    &.full {
        position: fixed;
        left: 0;
        right: 0;
        top: 80px;
        bottom: 0;
    }

    .canvas {
        // width: 100%;
        height: calc(100% - 128px);
        background: #ffffff;
        &.hide {
            position: absolute;
            left: -9999px;
            top: -9999px;
        }
    }

    #adaptive {
        height: calc(100vh - 80px);
        // min-width: 100%;
        position: relative;
        // overflow: hidden;

        #adaptiveBg {
            position: absolute;
            top: 100px;
            left: 30px;
            min-width: calc(100% - 60px);
            height: calc(100% - 100px);

            &.nowrap {
                white-space: nowrap;
                overflow-x: auto; // 水平方向内容过多时显示滚动条
                overflow-y: hidden; // 垂直方向隐藏滚动条
            }
        }

        .branch-item {
            vertical-align: top;
            margin-bottom: 20px;
            display: inline-block;
            margin-top: 12px;

            .branch-content {
                width: 180px;
                position: relative;
                text-align: center;

                .branch-dot {
                    position: absolute;
                    left: calc(50% - 3px);
                    top: -4px;
                    width: 6px;
                    height: 6px;
                    background: #d9a116;
                    border-radius: 50%;
                }

                .branch-line {
                    display: inline-block;
                    height: 150px;
                    width: 1px;
                    position: relative; // 为箭头定位
                }
                .branch-img {
                    width: 140px;
                    height: 150px;
                    position: absolute;
                    left: calc(50% - 70px);
                    top: 50px;

                    img {
                        width: 100%;
                        height: 100%;
                    }
                }
                .branch-div-img{
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    bottom: -2px;
                    z-index: 99;
                }
                .branch-div-table{
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    bottom: -34px;
                    .branch-div{
                        color: #fff;
                        font-size: 12px;
                        background: #529b2e;
                        width: 60px;
                        height: 20px;
                        line-height: 20px;
                        border-radius: 2px;
                        margin: 0 auto;
                    }
                }
                .branch-name {
                    color: #fff;
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    bottom: -54px;
                    max-width: 76%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
                .branch-name-gh {
                    color: #fff;
                    position: absolute;
                    left: 50%;
                    transform: translateX(20%);
                    bottom: 40px;
                    max-width: 76%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    font-size: 10px;
                }
                .sub-branch-container {
                    color: #fff;
                    position: absolute;
                    // left: 50%;
                    // transform: translateX(-50%);
                    padding-left: 80px;
                    bottom: -370px;
                }

                .branch-master-name {
                    position: absolute;
                    right: 0;
                    top: -8px;
                    font-size: 12px;
                    transform: translateX(50%);
                    color: #ffffff;
                    padding: 1px 3px;
                    max-width: 100%;
                    z-index: 1;
                    right: 50%;
                    &.right {
                        right: 0;
                    }

                    &.middle {
                        right: 50%;
                    }

                    &.none {
                        display: none;
                    }
                }
                .branch-master-name2{
                    max-width: 76%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }

            .branch-contact {
                width: 105px;
                height: 50px;
                margin-left: -10px;
                margin-right: -10px;
                border: 2px solid #007eff;
                border-top: none;
                margin-top: 2px;
                position: relative;
            }

            .branch-empty {
                width: 80px;
            }
        }

        &.fixed {
            height: 100%;
        }
    }

    #canvasTable {
        position: absolute;

        // background: #ff0000;
        .table-wrap {
            position: absolute;
        }

        .table-data {
            transform: translate(-50%, 0);
            margin-bottom: 20px;
            border-left: 1px solid #ccc;
            border-top: 1px solid #ccc;

            td {
                text-align: center;
                color: #fff;
                min-width: 38px;
                border-right: 1px solid #ccc;
                border-bottom: 1px solid #ccc;
                font-size: 12px;
                padding: 2px 2px;
                max-width: 60px;

                &.error {
                    color: #ff0000;
                }

                &.warning {
                    color: #faad14;
                }
            }
        }
    }

    .control {
        position: absolute;
        top: 28px;
        left: 0;
        right: 0;
        line-height: 50px;
        height: 50px;
        color: #fff;
        font-size: 16px;
        // overflow: hidden;
        text-align: center;

        .title {
            display: inline-block;
            font-size: 20px;
            font-weight: bold;
            letter-spacing: 2px;
        }

        .status {
            position: absolute;
            left: 30px;
            top: 0;

            .icon {
                display: inline-block;
                width: 14px;
                height: 14px;
                border-radius: 50%;
                border: 1px solid #fff;
            }

            span,
            .icon {
                vertical-align: middle;
            }

            .icon-success {
                background: #04a635;
            }

            .icon-error {
                background: #ca0003;
            }
        }

        .btn {
            position: absolute;
            right: 30px;
            top: 0;

            .text {
                color: #ffffff;
                font-size: 14px;
            }
        }
    }

    .alarm {
        position: absolute;
        top: 100px;
        min-height: 40px;
        left: 50%;
        transform: translateX(-50%);
        background: #5a1212;
        border: solid 2px #ff0000;
        box-shadow: 0px 0px 6px #ff0000;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 50px 0 20px;
        color: #fff;
        animation: alarmShadow 2s infinite alternate;

        .alarm-icon {
            margin-right: 10px;
            width: 26px;
            height: 26px;
        }

        .alarm-close {
            position: absolute;
            right: 0;
            top: 0;
            height: 100%;
            padding: 0 10px;
            font-size: 22px;
            display: flex;
            align-items: center;
            cursor: pointer;
        }
    }

    .footer {
        position: absolute;
        bottom: 0;
        left: 30px;
        right: 30px;
        line-height: 50px;

        .date {
            float: right;
            color: #e1e1e1;
            font-size: 16px;
        }
    }
}
</style>
